import { Table, Button, Checkbox, message, DatePicker, Image } from 'antd';
import { useState, useEffect } from 'react';
import type { TableProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import PageLayout from '../../components/Layout/PageLayout';
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import type { RootState } from '../../store';
import { addBookBorrow } from '../../api/bookBorrowController';

interface BookListItem {
    id: number;
    bookName: string;
    author: string;
    cover: string;
    startDate: string;
    endDate: string;
    selected: boolean;
}

const MyBookList = () => {
    const navigate = useNavigate();
    const loginUser = useSelector((state: RootState) => state.loginUser);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [bookList, setBookList] = useState<BookListItem[]>([]);

    useEffect(() => {
        if (!loginUser.id) {
            message.error('请先登录');
            navigate(-1);
            return;
        }

        // 从 localStorage 加载书单
        const savedList = JSON.parse(localStorage.getItem('bookList') || '[]');
        setBookList(savedList);
    }, [loginUser.id, navigate]);

    const handleDateChange = (id: number, dateType: 'startDate' | 'endDate', date: dayjs.Dayjs | null) => {
        setBookList(prev =>
            prev.map(item => {
                if (item.id === id) {
                    const newDate = date ? date.format('YYYY-MM-DD') : null;
                    
                    if (dateType === 'startDate' && item.endDate && newDate && dayjs(item.endDate).isBefore(newDate)) {
                        return {
                            ...item,
                            startDate: newDate,
                            endDate: dayjs(newDate).add(1, 'day').format('YYYY-MM-DD')
                        };
                    }
                    
                    return {
                        ...item,
                        [dateType]: newDate
                    };
                }
                return item;
            })
        );
        // 更新 localStorage
        localStorage.setItem('bookList', JSON.stringify(bookList));
    };

    const columns: TableProps<BookListItem>['columns'] = [
        {
            title: '图书封面',
            dataIndex: 'cover',
            key: 'cover',
            width: 150,
            render: (cover) => (
                <Image
                    src={cover}
                    alt="book cover"
                    width={64}
                    height={80}
                    className="object-cover rounded"
                    preview={{
                        mask: '点击预览',
                        maskClassName: 'rounded'
                    }}
                    fallback="error"
                />
            ),
        },
        {
            title: '图书名称',
            dataIndex: 'bookName',
            key: 'bookName',
            width: 200,
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
            width: 150,
        },
        {
            title: '借阅起始日期',
            dataIndex: 'startDate',
            key: 'startDate',
            width: 200,
            render: (date, record) => (
                <DatePicker
                    value={date ? dayjs(date) : null}
                    onChange={(newDate) => handleDateChange(record.id, 'startDate', newDate)}
                    placeholder="选择起始日期"
                    style={{ width: '100%' }}
                />
            ),
        },
        {
            title: '借阅截止日期',
            dataIndex: 'endDate',
            key: 'endDate',
            width: 200,
            render: (date, record) => (
                <DatePicker
                    value={date ? dayjs(date) : null}
                    onChange={(newDate) => handleDateChange(record.id, 'endDate', newDate)}
                    placeholder="选择截止日期"
                    style={{ width: '100%' }}
                />
            ),
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            render: (_, record) => (
                <Button type="link" danger onClick={() => handleDelete(record.id)}>
                    删除
                </Button>
            ),
        },
    ];

    const handleDelete = (id: number) => {
        const newList = bookList.filter(item => item.id !== id);
        setBookList(newList);
        localStorage.setItem('bookList', JSON.stringify(newList));
        message.success('删除成功');
    };

    const handleBatchBorrow = async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要借阅的图书');
            return;
        }

        const selectedBooks = bookList.filter(book => selectedRowKeys.includes(book.id));
        const borrowData = selectedBooks.map(book => ({
            bookid: book.id,
            bookname: book.bookName,
            borrowtime: book.startDate,
            returntime: book.endDate
        }));

        try {
            const response = await addBookBorrow(borrowData);
            if (response.code === 200) {
                message.success('批量借阅成功');
                // 从书单中移除已借阅的书籍
                const newList = bookList.filter(book => !selectedRowKeys.includes(book.id));
                setBookList(newList);
                localStorage.setItem('bookList', JSON.stringify(newList));
                setSelectedRowKeys([]);
            } else {
                message.error(response.msg || '借阅失败');
            }
        } catch (error) {
            console.error('借阅失败:', error);
            message.error('借阅失败，请稍后重试');
        }
    };

    return (
        <PageLayout>
            <div className="p-6">
                <div className="bg-white rounded-lg shadow">
                    <div className="p-4">
                        <Table
                            columns={columns}
                            dataSource={bookList}
                            rowKey="id"
                            scroll={{ x: 1000 }}
                            rowSelection={{
                                selectedRowKeys,
                                onChange: (keys) => setSelectedRowKeys(keys),
                            }}
                        />
                    </div>
                    
                    <div className="p-4 border-t flex justify-between items-center">
                        <div className="flex items-center">
                            <Checkbox
                                checked={selectedRowKeys.length === bookList.length}
                                onChange={(e) => {
                                    const keys = e.target.checked ? bookList.map(item => item.id) : [];
                                    setSelectedRowKeys(keys);
                                }}
                            >
                                全选
                            </Checkbox>
                            <span className="ml-4">
                                已选择 {selectedRowKeys.length} 项
                            </span>
                        </div>
                        <Button type="primary" onClick={handleBatchBorrow}>
                            批量借阅
                        </Button>
                    </div>
                </div>
            </div>
        </PageLayout>
    );
};

export default MyBookList; 